<template>
  <div class="chart-container">
    <slot></slot>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import 'echarts-liquidfill'; // 引入水球图扩展
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([CanvasRenderer]); // 水球图可能不需要其他组件

const chartRef = ref(null);
let chartInstance = null;

const option = ref({ // 积极情绪 - Liquid Fill Option (Copied from Home.vue)
  series: [{
    type: 'liquidFill', data: [0],
    color: ['rgba(0, 255, 255, 0.6)', 'rgba(0, 229, 238, 0.4)', 'rgba(64, 224, 208, 0.2)'],
    radius: '85%',
    label: {
        fontSize: 18, color: '#0ff', insideColor: '#fff',
        formatter: function(param) { return `${(param.value * 100).toFixed(1)}%`; }
    },
     outline: {
        show: true, borderDistance: 3,
        itemStyle: {
            color: 'none', borderColor: 'rgba(0, 255, 255, 0.5)', borderWidth: 2,
            shadowBlur: 10, shadowColor: 'rgba(0, 255, 255, 0.5)'
        }
    },
    backgroundStyle: { color: 'rgba(10, 23, 62, 0.5)' },
    itemStyle: { shadowBlur: 0 }
  }]
});

// 注意：水球图的数据依赖于整体情感分析接口
const initChart = async () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  try {
    const response = await axios.get('/api/overall_sentiment');
    if (response.data.code === 200) {
        let jijiData = response.data.data.find(item => item.name === '积极');
        let xiaojiData = response.data.data.find(item => item.name === '消极');
        let jiji = jijiData ? jijiData.value : 0;
        let xiaoji = xiaojiData ? xiaojiData.value : 0;
        let total = jiji + xiaoji;
        option.value.series[0].data = total > 0 ? [jiji / total] : [0];
        chartInstance.setOption(option.value);
    } else {
        console.error("Chart4_1 Error:", response.data.msg);
    }
  } catch (error) {
    console.error("Chart4_1 Network Error:", error);
  }
};

const resizeHandler = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
  chartInstance?.dispose();
});
</script>

<style scoped>
.chart-container { width: 100%; height: 100%; display: flex; flex-direction: column; }
.chart-content { flex-grow: 1; width: 100%; height: 100%; }
</style>